// pages/pro_detail/pro_detail.js
var common = require("../../common/common.js").common;

var WxParse = require("../../wxParse/wxParse.js");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        showInfoTip: false,
        //授权失败的弹框
        currentSwiper: 0,
        alert1: 0,
        alert: 0,
        close: 1,
        details: [],
        price: "",
        sku: "",
        buy_count: 1,
        sku_info: "",
        cart: [],
        product_id: 0,
        cart_count: 0,
        pid: "",
        goods: [],
        index_msg: [],
        detail: "",
        btn_true: 1,
        leader_id: "",
        warrant: true,
        custom_attributes_show: 0,
        color_header: "",
        color_main: "",
        color_minor: "",
        rich: "",
        details2: "",
        chooseCity: 0,
        options: "",
        s_leader: [],
        leader_id_share: "",
        chooseCity2: 0,
        nowCity: "",
        myleaderinfo: "",
        goodsId: "",
        isIPX: "",
        on_off_trans_free: 0,
        trans_for_free_barrier: 0,
        video_image: "",
        video: "",
        flash: 0,
        toastHide: true
    },
    //判断用户是否是新用户
    isNewCustomer(id) {
        let that = this;
        common.request({
            endpoint: "product/new_customer_judge",
            method: "post",
            data: {
                open_id: wx.getStorageSync("user").openid,
                id: id
            },
            success: res => {
                var details = that.data.details;
                var sku_info = that.data.sku_info;
                var buy_count = that.data.buy_count;
                var id = that.data.goodsId;
                var sku_id = sku_info.item_id;
                let sku_item = sku_info.item_id + "," + buy_count;
                if (res.code == 0) {
                    if (sku_info.stock_number >= buy_count) {
                        wx.navigateTo({
                            url: "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 0 + "&newuserprice=" + sku_info.new_customer_price
                        });
                    } else {
                        wx.showToast({
                            title: "库存不足",
                            icon: "none"
                        });
                    }
                } else {
                    that.toastControl("此商品只能新用户购买哟");
                }
            },
            fail() {
                that.toastControl("此商品只能新用户购买哟");
            }
        });
    },
    /** 
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        var isIPX = app.globalData.isIPX;
        this.setData({
            isIPX: isIPX,
            domain: app.globalData.domain.slice(0, -10)
        });
        let that = this;
        var scene = decodeURIComponent(options.scene);
        var s_leader = scene.split(":");
        that.setData({
            options: options,
            s_leader: s_leader
        });
        let warrant = common.checkUserWarrant();
        this.setData({
            warrant: warrant
        });
        this.getBase();
        this.getMyLeaderInfo2();
    },
    getMyLeaderInfo: function(leader_id_share) {
        var that = this;
        common.request({
            endpoint: "leader/myleaderinfo",
            method: "post",
            data: {
                openid: wx.getStorageSync("user").openid
            },
            success: res => {
                this.setData({
                    myleaderinfo: res.extra
                });
                var leaderid = that.data.options.my_leaderID;
                if (!!leaderid && !!res.extra.leader_id && res.extra.leader_id != leaderid) {
                    wx.showModal({
                        title: "当前商品所属团长不是您的团长",
                        content: "是否切换团长",
                        success(res) {
                            if (res.confirm) {
                                common.request({
                                    endpoint: "member/save_leader_id",
                                    method: "post",
                                    data: {
                                        leader_id: leader_id_share,
                                        openid: wx.getStorageSync("user").openid
                                    },
                                    success: res => {
                                        that.setData({
                                            myleaderinfo: res.extra
                                        });
                                        wx.showToast({
                                            title: "切换团长成功",
                                            icon: "none"
                                        });
                                    }
                                });
                            } else {
                                wx.showToast({
                                    title: "未切换团长",
                                    icon: "none"
                                });
                            }
                        },
                        fail() {}
                    });
                } else {}
            }
        });
    },
    getMyLeaderInfo2: function() {
        var that = this;
        var leader_id_share = that.data.leader_id_share;
        common.request({
            endpoint: "leader/myleaderinfo",
            method: "post",
            data: {
                leader_id_share: leader_id_share,
                openid: wx.getStorageSync("user").openid
            },
            success: res => {
                this.setData({
                    myleaderinfo: res.extra
                });
            }
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    alert_close: function() {
        var alert = this.data.alert;
        if (alert == 0) {
            alert = 1;
        } else {
            alert = 0;
        }
        this.setData({
            alert: alert
        });
    },
    alert_close2: function() {
        var alert1 = this.data.alert1;
        if (alert1 == 0) {
            alert1 = 1;
        } else {
            alert1 = 0;
        }
        this.setData({
            alert1: alert1
        });
    },
    alert_send: function() {
        var alert1 = this.data.alert1;
        if (alert1 == 0) {
            alert1 = 1;
        } else {
            alert1 = 0;
        }
        this.setData({
            alert1: alert1
        });
    },
    makeposter: function() {
        wx.navigateTo({
            url: "/pages/share2/share2?img=" + this.data.details.icon_img + "&title=" + this.data.details.name + "&price=" + this.data.details.low_price + "&my_leaderID=" + this.data.myleaderinfo.leader_id + "&productId=" + this.data.product_id
        });
    },
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        common.getCart();
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {
        var that = this;
        var code = wx.getStorageSync("code");
        this.setData({
            alert1: 0
        });
        var details = that.data.details;
        var product_id = that.data.product_id;
        var my_leaderID = this.data.myleaderinfo.leader_id;
        if (my_leaderID > 0) {
            if (details.is_one_item == 1) {
                return {
                    title: "仅" + this.data.details.low_new_price + this.data.details.name,
                    imageUrl: this.data.details.icon,
                    path: "/pages/new_user_pro_detail/new_user_pro_detail?id=" + product_id + "&my_leaderID=" + my_leaderID + "&code=" + code
                };
            } else {
                return {
                    title: "仅" + this.data.details.low_new_price + "起 " + this.data.details.name,
                    imageUrl: this.data.details.icon,
                    path: "/pages/new_user_pro_detail/new_user_pro_detail?id=" + product_id + "&my_leaderID=" + my_leaderID + "&code=" + code
                };
            }
        } else {
            if (details.is_one_item == 1) {
                return {
                    title: "仅" + this.data.details.low_price + this.data.details.name,
                    imageUrl: this.data.details.icon,
                    path: "/pages/new_user_pro_detail/new_user_pro_detail?id=" + product_id + "&code=" + code
                };
            } else {
                return {
                    title: "仅" + this.data.details.low_price + "起" + this.data.details.name,
                    imageUrl: this.data.details.icon,
                    path: "/pages/new_user_pro_detail/new_user_pro_detail?id=" + product_id + "&code=" + code
                };
            }
        }
    },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarTitle({
                    title: res.extra.title
                });
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    on_off_trans_free: res.extra.on_off_trans_free,
                    trans_for_free_barrier: res.extra.trans_for_free_barrier
                });
                var is_mcity = res.extra.is_mcity;
                var s_leader = that.data.s_leader;
                var options = that.data.options;
                var goodsId;
                if (options.id) {
                    goodsId = options.id;
                } else {
                    goodsId = s_leader[1];
                }
                that.setData({
                    goodsId: goodsId
                });
                if (is_mcity == 1) {
                    var leader_id_share;
                    if (options.my_leaderID) {
                        leader_id_share = options.my_leaderID;
                        that.setData({
                            chooseCity2: 1,
                            chooseCity: 0,
                            code: options.code
                        });
                        that.getNowCity();
                    } else {
                        if (s_leader[3]) {
                            leader_id_share = s_leader[3];
                            that.setData({
                                chooseCity2: 1,
                                chooseCity: 0,
                                code: s_leader[5]
                            });
                            that.getNowCity();
                        } else {
                            if (wx.getStorageSync("code")) {
                                that.setData({
                                    chooseCity: 0,
                                    chooseCity2: 0
                                });
                            } else {
                                that.setData({
                                    chooseCity: 1,
                                    chooseCity2: 0
                                });
                            }
                            leader_id_share = "";
                            wx.getStorage({
                                key: "user",
                                success(res) {
                                    that.getMyLeaderInfo(leader_id_share);
                                    //我的团长信息
                                                                },
                                fail() {
                                    setTimeout(() => {
                                        that.getMyLeaderInfo(leader_id_share);
                                        //我的团长信息
                                                                        }, 1500);
                                }
                            });
                        }
                    }
                    that.setData({
                        leader_id_share: leader_id_share
                    });
                } else {
                    var leader_id_share;
                    if (options.my_leaderID) {
                        leader_id_share = options.my_leaderID;
                    } else {
                        if (s_leader[3]) {
                            leader_id_share = s_leader[3];
                        } else {
                            leader_id_share = "";
                        }
                    }
                    wx.getStorage({
                        key: "user",
                        success(res) {
                            that.getMyLeaderInfo(leader_id_share);
                            //我的团长信息
                                                },
                        fail() {
                            setTimeout(() => {
                                that.getMyLeaderInfo(leader_id_share);
                                //我的团长信息
                                                        }, 1500);
                        }
                    });
                    that.setData({
                        chooseCity: 0,
                        chooseCity2: 0,
                        leader_id_share: leader_id_share
                    });
                }
                that.getData();
                that.getDetail();
            }
        });
    },
    swiperChange: function(e) {
        this.setData({
            currentSwiper: e.detail.current
        });
    },
    close_alert: function(e) {
        this.setData({
            alert: 0
        });
    },
    getData: function() {
        var that = this;
        var id = that.data.goodsId;
        common.request({
            endpoint: "product/product_info",
            method: "post",
            data: {
                id: id,
                visit_type: 1
            },
            success: res => {
                let details = res.extra;
                let custom_attributes_show = 0;
                for (var i = 0; i < details.custom_attributes.length; i++) {
                    if (details.custom_attributes[i]["show"] == 1) {
                        custom_attributes_show++;
                    }
                }
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = this.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = this.getProductBySku(details.sku, sku);
                that.setData({
                    custom_attributes_show: custom_attributes_show,
                    details: details,
                    sku: sku,
                    product_id: id,
                    sku_info: sku_info,
                    video_image: details.video_img,
                    video: details.video
                });
            }
        });
    },
    /** 
   * 添加 sku 属性
   */
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let sku = this.data.sku;
        sku = this.reBlanceSku(sku, key_id, value_id);
        let attribute = this.data.details.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        let sku_info = this.getProductBySku(this.data.details.sku, sku);
        this.setData({
            sku: sku,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info
        });
    },
    /** 
   * 重平衡 sku
   * key_id: integer
   */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /** 
   * 重建 sku
   */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /** 
   * 对选择的 sku 属性进行排序
   */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /** 
   * 分割现有 sku 成对象数组
   */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /** 
   * 添加一个 sku
   */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /** 
   * 选择 sku
   */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value = values;
        }
        return attribues;
    },
    /** 
   * 选择单个 sku 属性
   */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    /**
   * 根据 sku 获取物品
   */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    save_count: function(e) {
        if (parseInt(e.detail.value > that.data.newUserBuyLimit)) {
            //判断数值大小有没有超过购买上限
            //超过上限，设置为上限值
            this.setData({
                buy_count: that.data.newUserBuyLimit
            });
        } else {
            this.setData({
                buy_count: parseInt(e.detail.value)
            });
        }
    },
    blur: function(e) {
        let count = e.detail.value;
        if (count <= 0) {
            count = 1;
        }
        this.setData({
            buy_count: parseInt(count)
        });
    },
    reduce_count: function() {
        let buy_count = this.data.buy_count;
        if (buy_count > 1) {
            buy_count--;
        }
        this.setData({
            buy_count: buy_count
        });
    },
    add_count: function(e) {
        let buy_count = this.data.buy_count;
        let restrictions = this.data.newUserBuyLimit;
        if (restrictions == 0) {
            buy_count++;
        } else {
            if (buy_count >= restrictions) {
                wx.showModal({
                    title: "提示",
                    content: "本商品限购" + restrictions + "份"
                });
            } else {
                buy_count++;
            }
        }
        this.setData({
            buy_count: buy_count
        });
    },
    join_goods: function() {
        var that = this;
        var alert = that.data.alert;
        if (alert == 0) {
            this.setData({
                alert: 1,
                btn_true: 1
            });
        } else {
            var cart_count = wx.getStorageSync("cart_count") || 0;
            var details = that.data.details;
            var sku_info = that.data.sku_info;
            var buy_count = that.data.buy_count;
            var id = that.data.product_id;
            cart_count = cart_count + buy_count;
            var cart = wx.getStorageSync("cart") || [];
            if (cart_count <= 99999) {
                if (sku_info.stock_number >= buy_count) {
                    if (cart == "") {
                        let goods = {
                            id: sku_info.item_id,
                            product_id: id,
                            img: details.icon_img,
                            title: details.name,
                            varieties: sku_info.title,
                            price: sku_info.price,
                            o_price: sku_info.o_price,
                            count: buy_count,
                            stock_number: sku_info.stock_number,
                            select: 1,
                            proID: id,
                            status: 1
                        };
                        wx.showToast({
                            title: "加入购物车成功",
                            icon: "success",
                            success: res => {
                                wx.setStorage({
                                    key: "cart_count",
                                    data: cart_count
                                });
                                this.setData({
                                    cart_count: cart_count
                                });
                                var cart = wx.getStorageSync("cart") || that.data.cart;
                                cart.push(goods);
                                wx.setStorage({
                                    key: "cart",
                                    data: cart
                                });
                                that.setData({
                                    buy_count: 1,
                                    alert: 0
                                });
                            }
                        });
                    } else {
                        var total = 0;
                        var index = 0;
                        for (var i = 0; i < cart.length; i++) {
                            if (sku_info.item_id != cart[i]["id"]) {
                                total++;
                            } else {
                                index = i;
                                break;
                            }
                        }
                        if (total == cart.length) {
                            let goods = {
                                id: sku_info.item_id,
                                product_id: id,
                                img: details.icon_img,
                                title: details.name,
                                varieties: sku_info.title,
                                price: sku_info.price,
                                o_price: sku_info.o_price,
                                count: buy_count,
                                stock_number: sku_info.stock_number,
                                select: 1,
                                proID: id,
                                status: 1
                            };
                            wx.showToast({
                                title: "加入购物车成功",
                                icon: "success",
                                success: res => {
                                    wx.setStorage({
                                        key: "cart_count",
                                        data: cart_count
                                    });
                                    this.setData({
                                        cart_count: cart_count
                                    });
                                    var cart = wx.getStorageSync("cart") || that.data.cart;
                                    cart.push(goods);
                                    wx.setStorage({
                                        key: "cart",
                                        data: cart
                                    });
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0
                                    });
                                }
                            });
                        } else {
                            cart[index]["count"] = cart[index]["count"] + buy_count;
                            wx.showToast({
                                title: "加入购物车成功",
                                icon: "success",
                                success: res => {
                                    wx.setStorage({
                                        key: "cart_count",
                                        data: cart_count
                                    });
                                    this.setData({
                                        cart_count: cart_count
                                    });
                                    wx.setStorage({
                                        key: "cart",
                                        data: cart
                                    });
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0
                                    });
                                }
                            });
                        }
                    }
                } else {
                    wx.showToast({
                        title: "加入购物车失败",
                        icon: "none"
                    });
                }
            } else {
                wx.showToast({
                    title: "购物车最多加99999个商品！",
                    icon: "none"
                });
            }
        }
    },
    buy: function() {
        var that = this;
        var alert = that.data.alert;
        if (alert == 0) {
            this.setData({
                alert: 1,
                btn_true: 2
            });
        } else {
            that.isNewCustomer(that.data.options.id);
        }
    },
    getIndexMes: function() {
        var that = this;
        common.request({
            endpoint: "order/index_msg",
            method: "post",
            success: res => {
                that.setData({
                    index_msg: res.extra
                });
            }
        });
    },
    getUserInfo: function() {
        var that = this;
        var id = this.data.goodsId;
        common.getUserInfo();
        var leader_id_share = that.data.leader_id_share;
        common.getUserInfo();
        setTimeout(() => {
            that.getMyLeaderInfo(leader_id_share);
            //我的团长信息
                }, 3e3);
    },
    getDetail: function() {
        var that = this;
        var id = that.data.goodsId;
        common.request({
            endpoint: "product/product_info",
            method: "post",
            data: {
                id: id,
                visit_type: 2
            },
            success: res => {
                let details = res.extra;
                that.setData({
                    details2: details,
                    detail: WxParse.wxParse("detail", "html", details.detail, that, 0),
                    rich: WxParse.wxParse("rich", "html", details.rich, that, 0),
                    newUserBuyLimit: res.extra.new_limit
                });
                common.request({
                    endpoint: "product/class_product",
                    method: "post",
                    data: {
                        pid: details.cid
                    },
                    success: res => {
                        that.setData({
                            goods: res.extra[0].sub
                        });
                    }
                });
            }
        });
    },
    continueGetSet: function() {
        let that = this;
        wx.getSetting({
            success(res) {}
        });
        wx.openSetting({
            success(res) {
                if (res.authSetting["scope.userInfo"]) {
                    that.getUserInfo();
                }
                if (res.authSetting["scope.userLocation"]) {}
                if (that.data.warrant && res.authSetting["scope.userLocation"] || res.authSetting["scope.userInfo"] && res.authSetting["scope.userLocation"]) {
                    that.setData({
                        showInfoTip: false
                    });
                }
            }
        });
    },
    video: function() {
        this.setData({
            flash: 1
        });
    },
    //提示框
    toastControl(content, time) {
        var that = this;
        that.setData({
            toastContent: content,
            toastHide: false
        });
        //显示提示框
                setTimeout(() => {
            that.setData({
                toastHide: true
            });
        }, !time ? 3e3 : time);
        //定时隐藏提示框,默认3秒后隐藏
        }
});